app.controller("HeaderController", ['$scope', '$rootScope', '$location', 'navigationService', 'snsService', function($scope, $rootScope, $location, navigationService, snsService){
	$scope.submit = function(){
		console.log("logout!!");
	}
	$scope.back = function(){
		navigationService.back();
	}
	$rootScope.isPending = true;
	initRootScope($rootScope);

	var navBackEventCall=function(evt){
		Log.log("handle NAVIGATION_BACK_EVENT ")
		navigationService.back();
	};
	document.removeEventListener("NAVIGATION_BACK_EVENT",navBackEventCall, false);
	document.addEventListener("NAVIGATION_BACK_EVENT",navBackEventCall, false);
	
	$scope.iOS7 = iOS7();
	$scope.createClub = function(){
		$location.path("/createClub");
	} 
	$scope.removeAction = function(){
		$rootScope.$emit("REMOVE_ACTIONS_EVENT");
	}
	/*
	var getAuthToken = function(options){
		promise = $http({                
			method: 'POST',
			url: "http://qa.yunchelife.com/api/v1/User/Login",
			data: options,
			headers: {'Content-Type': 'application/json;charset=utf-8'}
		}).then(function(response){
			return response.data;
		});
		return promise;
	};
	getAuthToken({
		"phoneNum": "18930843026",
		"password": "111111"
	}).then(function(data){
		console.log(data);
	});
	*/
	snsService.getProfile().then(function(data){

		$rootScope.userProfile = data;
		$rootScope.isPending = false;

	});
	snsService.getReportReasons().then(function(data){
		$rootScope.reportReasons = data.data;

		$rootScope.isPending = false;

	});

    // for treasury exam
	$scope.submit = function () {
	    if ($rootScope.submitAction) {
	        $rootScope.submitAction();
	    }
	};
}]);

app.controller("FooterController", ['$scope', '$location', "$rootScope", "$routeParams","snsService", function($scope, $location, $rootScope, $routeParams,snsService){
	$scope.createTopic = function(){
		$location.path("/createTopic/" + $routeParams.snsClubId);
	};
	$scope.createReply = function(){
		console.log("emit add reply event")
		$rootScope.$emit("ADD_REPLY_EVENT");
	};
	$scope.myClub = function(){
		$location.path("/myforum");
	};

	$scope.goforum = function () {
		snsService.getClubByName(TRAFFIC_ANSWER_SNS_CLUB_NAME).then(function(resp){
			$location.path("/club/"+resp.data.snsClubId);
		});
	}
}]);

app.controller("HomeController", ['$location', '$scope', "$rootScope", function($location, $scope, $rootScope){
	$rootScope.pageTitle = "";
	$rootScope.pageClass = "page-login";
	$rootScope.showBackButton = false;	
	$rootScope.canCreateTopic = false;
	

}]);

app.controller("ClubsController", ['$location','$scope', "$rootScope", "snsService", function($location, $scope, $rootScope, snsService){
	$rootScope.pageTitle = "微社区";
	$rootScope.pageClass = "page-clubs";
    initRootScope($rootScope);
	$rootScope.hasFooter = true;
	$rootScope.hasMyForum = true;
	$rootScope.isPending = true;

    $scope.isLoading = true;
    $scope.showTopics = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$scope.mctopicMode=mctopicDirectiveMode.list;// 有两个值list和single,list表明话题以list形式显示 如在所有话题，single单独显示，如在话题明细中
	var totalPage = 1;

	var curPage = 1, numPerPage = 10;

	var loadMoreEventHandler = function(evt){
		
		if($scope.isLoading)
			return;

		$scope.isLoading = true;
		
		/*
		snsService.getTopics({"snsclubid":"","page":curPage,"countPerPage":numPerPage,"sortOption":1}).then(function(data){
			curPage = data.data.page;
			$rootScope.isPending = false;
			$scope.topics = $scope.topics.concat(data.data.topics);
			$scope.isLoading = false;
		});
		*/
		var md = $scope.topics[$scope.topics.length-1].modifiedDecimal;
		snsService.getTopicsAfterModified({"snsclubid":"","takeCount":numPerPage,"modifiedDecimal":md}).then(function(data){
			//console.log(data.data.topics[0].modifiedDecimal)
			if(data.data.topics.length){
				$scope.topics = $scope.topics.concat(data.data.topics);
				$scope.isLoading = false;
			}
			else{
				$scope.noMorePage = true;
			}
		});
	};

	var getTopics = function(){
		$rootScope.isPending = true;
		//SNS/GetTopicsAfterModified?snsClubId={snsClubId}&modifiedDecimal={modifiedDecimal}&takeCount={takeCount}
		snsService.getTopicsAfterModified({"snsclubid":"","takeCount":numPerPage,"modifiedDecimal":""}).then(function(data){
			$scope.topics = data.data.topics;
			$rootScope.isPending = false;
		});
	};
	// remove the event listener
	$rootScope.$$listeners["LOAD_MORE_TITLES_EVENT"]=[];
	$rootScope.$$listeners["REFRESH_TITLES_EVENT"]=[];
	$rootScope.$on("LOAD_MORE_TITLES_EVENT", loadMoreEventHandler);
	$rootScope.$on("REFRESH_TITLES_EVENT", getTopics);

	var getPageInfo = function(){

		snsService.getUserClubs({"userId": $rootScope.userProfile.userId}).then(function(data){
			console.log("++++++++ afas e +++++++");
			console.log(data);
			if(data.status==0){
				$rootScope.isPending = false;
				$rootScope.myClubs = data.data;
			}
		});
		snsService.getMyUnreadMsgCnt().then(function(data){
			if(data.status==0){
				$rootScope.isPending = false;
				$rootScope.unreadMsgCnt = data.data.unreadMsgCnt;
			}
		});
		
		snsService.getRecommendedClubs().then(function(data){
			
			if(data.status==0){
				$rootScope.isPending = false;
				$scope.recommendedClubs = data.data;
			}
		});
		snsService.getClubs({"page":1,"countPerPage":10,"sortClubOption":1,"countPerPage":30}).then(function(data){
			
			if(data.status==0){
				$rootScope.isPending = false;
				$scope.rankClubs = data.data.clubs;
			}
		});
		getTopics();
	};
	if(!$rootScope.userProfile){
		snsService.getProfile().then(function(data){
			$rootScope.userProfile = data;
			getPageInfo();

		});
	}else{
		getPageInfo();
	}

	
	/*
	snsService.getTopics({"snsclubid":"","page":1,"countPerPage":numPerPage,"sortOption":1}).then(function(data){
		console.log(data)
		$scope.topics = data.data.topics;
		totalPage = data.data.totalPage;
	});
	*/
	$scope.submitSearch = function(searchKey){
		
		//console.log($scope.searchOption)
		if(!searchKey)
			return;
		$rootScope.isPending = true;
		snsService.searchClubs({"searchKey": searchKey}).then(function(data){
			$rootScope.isPending = false;
			if(data.status==0){
				$scope.isLoading = false;
				$scope.findClubs = data.data && data.data.length>0;
				$scope.searchResult = data.data;
				$scope.showSearchResult = true;
				$scope.showTopics = false;
				$scope.showClubs = false;
			}
		});
	};
	$scope.showAllTopics = function(){
		$scope.showSearchResult = false;
		$scope.showTopics = true;
		$scope.showClubs = false;
		$scope.searchOption = "";
	
	};
	$scope.showAllClubs = function(){
		$scope.showSearchResult = false;
		$scope.showTopics = false;
		$scope.showClubs = true;
		$scope.searchOption = "";
	};
	$scope.gotoClub = function(snsClubId){

		$rootScope.currentClub = snsClubId;
        $rootScope.canExit = false;
		$location.path("/club/" + snsClubId);
	};
}]);


app.controller("ClubController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = "微社区";
	$rootScope.pageClass = "page-club";
	initRootScope($rootScope);
	$rootScope.hasFooter = true;
	$rootScope.canCreateTopic = true;
	$rootScope.isPending = true;

	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$scope.mctopicMode=mctopicDirectiveMode.list;// 有两个值list和single,list表明话题以list形式显示 如在所有话题，single单独显示，如在话题明细中
	var totalPage = 1;

	var curPage = 1, numPerPage = 10;
	
	var isInMyClubs = function(clubId, needRemove){
		if(!$rootScope.myClubs){
			return false;
		}
		for(var i=0;i<$rootScope.myClubs.length;i++){
			if(clubId == $rootScope.myClubs[i].snsClubId){
				if(needRemove){
					$rootScope.myClubs.splice(i,1); 
					return true;
				}else{
					return true;
				}
			}
		}
		return false;
	}

	var loadMoreEventHandler = function(evt){
		
		if($scope.isLoading)
			return;

		/*
		snsService.getTopics({"snsclubid":$routeParams.snsClubId,"page":curPage,"countPerPage":numPerPage,"sortOption":1}).then(function(data){
			
			$rootScope.isPending = false;
			$scope.topics = $scope.topics.concat(data.data.topics);
		});
		*/
		var md = $scope.topics[$scope.topics.length-1].modifiedDecimal;
		snsService.getTopicsAfterModified({"snsclubid":$routeParams.snsClubId,"takeCount":numPerPage,"modifiedDecimal":md}).then(function(data){
			//console.log(data.data.topics[0].modifiedDecimal)
			if(data.data.topics.length){
				$scope.topics = $scope.topics.concat(data.data.topics);
				$scope.isLoading = false;
			}
			else{
				$scope.noMorePage = true;
			}
		});
	};

	var getTopics = function(){
		$rootScope.isPending = true;
		snsService.getTopicsAfterModified({"snsclubid":$routeParams.snsClubId,"takeCount":numPerPage,"modifiedDecimal":""}).then(function(data){
			$rootScope.isPending = false;
			$scope.topics = data.data.topics;
			
		});
	};
	// remove the event listener
	$rootScope.$$listeners["LOAD_MORE_TITLES_EVENT"]=[];
	$rootScope.$on("LOAD_MORE_TITLES_EVENT", loadMoreEventHandler);
	$rootScope.$on("REFRESH_TITLES_EVENT", getTopics);

	if(!$rootScope.myClubs){
		if(!$rootScope.userProfile){
			snsService.getProfile().then(function(data){
				if(data.status==0){				                               
					$rootScope.userProfile = data;
				}		
			});
		}else{
			snsService.getUserClubs({"userId": $rootScope.userProfile.userId}).then(function(data){
				if(data.status==0){
					$rootScope.myClubs = data.data;
				}
				$scope.isJoined = isInMyClubs($routeParams.snsClubId);
			});		
		}
	}else{
		$scope.isJoined = isInMyClubs($routeParams.snsClubId);
	}
	// get current club
	snsService.getClub($routeParams.snsClubId).then(function(data){
		
		if(data.status==0){
			$scope.club = data.data;
			$rootScope.currentClub = $routeParams.snsClubId;
			getTopics();
		}
	});

	$scope.joinClub = function(snsClubId){
		snsService.joinClub({"snsClubId":snsClubId}).then(function(data){
			var msg = "";
			if(data.status == 0){
				msg = data.friendlyMessage;
				if(!isInMyClubs(snsClubId)){
					if(!$rootScope.myClubs){
						$rootScope.myClubs = [];
					}
					$rootScope.myClubs.push($scope.club);
				}
				$scope.isJoined = true;
			}else{
				msg = data.friendlyMessage;
			}
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {							
						return {message:msg};
					}
				}
			});
			return;
		});
	};
	$scope.exitClub = function(snsClubId){
		console.log("exit club");
		snsService.exitClub({"snsClubId":snsClubId}).then(function(data){
			var msg = "";
			if(data.status == 0){
				msg = data.friendlyMessage;
				isInMyClubs(snsClubId, true);
				$scope.isJoined = false;
			}else{
				msg = data.friendlyMessage;
			}
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {							
						return {message:msg};
					}
				}
			});
			return;
		});
	}
	
}]);


app.controller("MyForumController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = "我的微社区";
	$rootScope.pageClass = "page-forum";
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = true;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;

	snsService.getUserClubInfo({"userId": $rootScope.userProfile.userId}).then(function(data){
		console.log("000000000")
		console.log(data)
		if(data.status==0){
			$rootScope.isPending = false;
			$scope.clubCnt = data.data.clubCnt;
			$scope.totalTopicCnt = data.data.totalTopicCnt;
			$scope.unreadMsgCnt = data.data.unreadMsgCnt;
			//$rootScope.userClubs = data.data;
		}
	});
	$scope.gotoMyClub = function(){
		$location.path("/myclub");
	};
	$scope.gotoMyTopic = function(){
		$location.path("/mytopic");
	};
	$scope.gotoMyAction = function(){
		$location.path("/myaction");
	};
}]);




app.controller("UserForumController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	if($rootScope.curUser&&$rootScope.curUser.userId==$rootScope.userProfile.userId)
		$rootScope.pageTitle = "我的微社区";
	else
		$rootScope.pageTitle = ($rootScope.curUser && $rootScope.curUser.gender<2?'他':'她') + "的微社区";
	$rootScope.pageClass = "page-forum";
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = false;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$scope.gotoMyClub = function(){
		$location.path("/userclub")
	};
	$scope.gotoMyTopic = function(){
		$location.path("/usertopic")
	};
	console.log("-------------------");
	console.log($rootScope.curUser)

	if($rootScope.curUser){
		snsService.getUserClubInfo({"userId": $rootScope.curUser.userId}).then(function(data){
			console.log("000000000")
			console.log(data)
			if(data.status==0){
				$rootScope.isPending = false;
				$scope.clubCnt = data.data.clubCnt;
				$scope.totalTopicCnt = data.data.totalTopicCnt;
				$scope.unreadMsgCnt = data.data.unreadMsgCnt;
				//$rootScope.userClubs = data.data;
			}
		});
	}


}]);




app.controller("MyClubController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = "我的社区";
	$rootScope.pageClass = "page-club";
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = false;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;

	if(!$rootScope.myClubs){
		snsService.getUserClubs({"userId": $rootScope.userProfile.userId}).then(function(data){
			if(data.status==0){
				$rootScope.isPending = false;
				$rootScope.myClubs = data.data;
			}
		});
	}
	$scope.gotoClub = function(snsClubId){
		$location.path("/myclub/" + snsClubId);
	}
}]);

app.controller("UserClubController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = ($rootScope.curUser && $rootScope.curUser.gender<2?'他':'她') + "的社区";
	$rootScope.pageClass = "page-club";
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = false;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	if($rootScope.curUser){
		snsService.getUserClubs({"userId": $rootScope.curUser.userId}).then(function(data){
			if(data.status==0){
				$rootScope.isPending = false;
				$rootScope.userClubs = data.data;
			}
		});
		/*
		snsService.getUserClubs({"userId": $rootScope.curUser.userId}).then(function(data){
			if(data.status==0){
				$rootScope.isPending = false;
				$rootScope.userClubs = data.data;
			}
		});
		*/
	}
	$scope.gotoClub = function(snsClubId){
		$location.path("/userclub/" + snsClubId);
	}
}]);


app.controller("MyTopicController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = "我的话题";
	$rootScope.pageClass = "page-topic";
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = true;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$scope.mctopicMode=mctopicDirectiveMode.list;// 有两个值list和single,list表明话题以list形式显示 如在所有话题，single单独显示，如在话题明细中
	var numPerPage = 10;
	
	var loadMoreEventHandler = function(evt){
		if($scope.isLoading)
			return;
		var md = $scope.topics[$scope.topics.length-1].modifiedDecimal;
		getTopics({"takeCount":numPerPage,"minModifiedDecimal":md,"userId": $rootScope.userProfile.userId},true);
	};


	var getTopics = function(params,concat){
		$rootScope.isPending = true;
		//SNS/GetTopicsAfterModified?snsClubId={snsClubId}&modifiedDecimal={modifiedDecimal}&takeCount={takeCount}
		snsService.getUserTopics(params).then(function(data){
			console.log("??????????? ", data)
			$rootScope.isPending = false;
			if(data.data.topics.length){
				if(!concat){

					$scope.topics = data.data.topics;
				}else{
					$scope.topics = $scope.topics.concat(data.data.topics);
				}
				$scope.isLoading = false;
			}else{
				$scope.noMorePage = true;
			}
		});
	};
	// remove the event listener
	$rootScope.$$listeners["LOAD_MORE_TITLES_EVENT"]=[];
	$rootScope.$$listeners["REFRESH_TITLES_EVENT"]=[];
	$rootScope.$on("LOAD_MORE_TITLES_EVENT", loadMoreEventHandler);
	$rootScope.$on("REFRESH_TITLES_EVENT", function(){
		getTopics({"takeCount":numPerPage,"minModifiedDecimal":"","userId": $rootScope.userProfile.userId});
	});
	if(!$rootScope.userProfile){
		snsService.getProfile().then(function(data){
			$rootScope.userProfile = data;
			getTopics({"takeCount":numPerPage,"minModifiedDecimal":"","userId": $rootScope.userProfile.userId});
		});
	}	
	else{
		getTopics({"takeCount":numPerPage,"minModifiedDecimal":"", "userId": $rootScope.userProfile.userId});
	}
	

}]);



app.controller("UserTopicController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = ($rootScope.curUser && $rootScope.curUser.gender<2?'他':'她') + "的话题";
	$rootScope.pageClass = "page-topic";
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = true;
	$rootScope.isPending = true;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$scope.mctopicMode=mctopicDirectiveMode.list;// 有两个值list和single,list表明话题以list形式显示 如在所有话题，single单独显示，如在话题明细中
	var numPerPage = 10;
	
	var loadMoreEventHandler = function(evt){
		if($scope.isLoading)
			return;
		var md = $scope.topics[$scope.topics.length-1].modifiedDecimal;
		getTopics({"userId": $rootScope.curUser.userId,"takeCount":numPerPage,"minModifiedDecimal":md},true);
	};


	var getTopics = function(params,concat){
		$rootScope.isPending = true;
		//SNS/GetTopicsAfterModified?snsClubId={snsClubId}&modifiedDecimal={modifiedDecimal}&takeCount={takeCount}
		snsService.getUserTopics(params).then(function(data){
			console.log("??????????? ", data)
			$rootScope.isPending = false;
			if(data.data.topics.length){
				if(!concat){

					$scope.topics = data.data.topics;
				}else{
					$scope.topics = $scope.topics.concat(data.data.topics);
				}
				$scope.isLoading = false;
			}else{
				$scope.noMorePage = true;
			}
		});
	};
	// remove the event listener
	$rootScope.$$listeners["LOAD_MORE_TITLES_EVENT"]=[];
	$rootScope.$$listeners["REFRESH_TITLES_EVENT"]=[];
	$rootScope.$on("LOAD_MORE_TITLES_EVENT", loadMoreEventHandler);
	$rootScope.$on("REFRESH_TITLES_EVENT", function(){
		getTopics({"userId": $rootScope.curUser.userId,"takeCount":numPerPage,"minModifiedDecimal":""});
	});
	if(!$rootScope.userProfile){
		snsService.getProfile().then(function(data){
			$rootScope.userProfile = data;
			getTopics({"userId": $rootScope.curUser.userId,"takeCount":numPerPage,"minModifiedDecimal":""});
		});
	}	
	else{
		getTopics({"userId": $rootScope.curUser.userId,"takeCount":numPerPage,"minModifiedDecimal":""});
	}
	

}]);


app.controller("TopicDetailController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = "话题详情";
	$rootScope.pageClass = "page-topic-detail";
	$rootScope.hasFooter = true;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = true;
	$rootScope.canRemoveAction = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = false;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$rootScope.isPending = true;
	$rootScope.isSharing = $location.search().sharing;
	$rootScope.canCreateReply = !$rootScope.isSharing;
	console.log($routeParams.snsTopicId)
	//SNS/GetTopicsAfterModified?snsClubId={snsClubId}&modifiedDecimal={modifiedDecimal}&takeCount={takeCount}
	snsService.getTopic($routeParams.snsTopicId).then(function(data){
		$scope.topic = data.data;
		$rootScope.isPending = false;
	});
}]);


app.controller("MyActionController", ['$location','$scope', "$rootScope", "$modal", "$routeParams","snsService",function($location, $scope, $rootScope, $modal, $routeParams,snsService){
	$rootScope.pageTitle = "我的互动";
	$rootScope.pageClass = "page-action";
	$rootScope.canRemoveAction = true;
	$rootScope.hasFooter = false;
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.hasMyForum = false;
	$rootScope.isPending = false;
	$scope.isJoined = false;
	$scope.inclub = true;
	$scope.isTapping = false;
	$scope.showMore = false;
	$scope.isLoading = false;
	$scope.noMorePage=false;


	var numPerPage = 30;
	
	var loadMoreEventHandler = function(evt){
		if($scope.isLoading)
			return;
		var md = "";
		if($scope.actions){
			md = $scope.actions[$scope.actions.length-1].createdDecimal;
		}
		
		getActions({"takeCount":numPerPage,"minCreatedDecimal":md},true);
	};


	var getActions = function(params,concat){
		$rootScope.isPending = true;
		//SNS/GetTopicsAfterModified?snsClubId={snsClubId}&modifiedDecimal={modifiedDecimal}&takeCount={takeCount}
		snsService.getMyInteractionMsgs(params).then(function(data){
			console.log("??????????? ", data)
			$rootScope.isPending = false;
			
			if(data.data.msgs.length){
				if(!concat){
					$scope.actions = data.data.msgs;
				}else{
					$scope.actions = $scope.actions.concat(data.data.msgs);
				}
				$scope.isLoading = false;
				$scope.showMore=true;
				if(data.data.msgs.length<numPerPage)//返回的数据<取得数，表明已经服务端数据已经取完了
				{
					$scope.noMorePage = true;
				}
			}else{
				$scope.noMorePage = true;
			}
			
		});
	};
	

	$rootScope.$$listeners["REMOVE_ACTIONS_EVENT"]=[];
	$rootScope.$on("REMOVE_ACTIONS_EVENT", function(){
		if(!$scope.actions){
			return;
		}
		var modalInstance = $modal.open({
			templateUrl: 'views/tmpl_modal_remove_interaction_msg_confirm.html',
			controller: ModalConfirmRemoveInteractionMsgCtrl,
			size: 'sm',
			resolve: {
				obj: function () {
					return {message:"确定要清空吗?",scope:$scope};
				}
			}
		});
	});
	//snsService.getSNSInteractionType().then(function(data){
		//console.log(data);
	getActions({"takeCount":numPerPage,"minCreatedDecimal":""});
	//})

	$scope.gotoTopic = function(snsTopicId){
		console.log("snsTopicId: " + snsTopicId);
		$location.path("/myaction/" + snsTopicId);
	};
	$scope.showMoreMsg = function(){
		loadMoreEventHandler();
	};
	$scope.gotoUsersClub = function(invokeUser){
		console.log("invokeUser");
		// curUser should not be one who has logged in.
		$rootScope.curUser = invokeUser;
		$location.path("/userforum")
	};

}]);


app.controller("CreateTopicController", ['$location','$scope', "$rootScope", "$routeParams","snsService",function($location, $scope, $rootScope, $routeParams,snsService){
	$rootScope.pageTitle = "微社区";
	$rootScope.canRemoveAction = false;
	$rootScope.pageClass = "page-topic";
	$rootScope.canCreateTopic = false;
	$rootScope.canCreateReply = false;
	$rootScope.showEmoji = false;

	$scope.uploadedImages = [];
	$scope.mobile = browser.versions.mobile;

	document.removeEventListener("FILE_UPLOADED_EVENT");
	document.addEventListener("FILE_UPLOADED_EVENT", function(evt){
		$rootScope.isPending = false;
        $scope.isUploadSuccess = true;
        $scope.uploadedImages.push(evt.data);
        $rootScope.$$phase || $rootScope.$apply();
        $scope.$$phase || $scope.$apply();
	}, false);
	
	document.removeEventListener("FILE_UPLOAD_CANCEL_EVENT");
	document.addEventListener("FILE_UPLOAD_CANCEL_EVENT", function(evt){
		$rootScope.isPending = false;
        $rootScope.$$phase || $rootScope.$apply();
	}, false);
	var contentEl = document.querySelector("textarea[name='topic-content']");

	$rootScope.$$listeners["EMOJI_SELECTED_EVENT"]=[];
	$rootScope.$on("EMOJI_SELECTED_EVENT",function(evt, args){
		contentEl.value = contentEl.value + args.emotion;
	});
		
	$scope.addTopic = function(){
		var content = document.querySelector("textarea[name='topic-content']").value;
		var title = document.querySelector("input[name='topic-title']").value;

		if($.emoticons.count(content) >8){
			$(".note-dialog").show();
			$(".note-dialog").addClass("note-dialog-show");
			setTimeout(function(){
				$(".note-dialog").hide();
				$(".note-dialog").removeClass("note-dialog-show");
			},4000);
			return;
		}
		
		var imgs = [];
		angular.forEach($scope.uploadedImages, function(obj){
			imgs.push(obj.fileUploadId);
		});
		//Log.log("in addTopic function", imgs)
		var param = {
			"snsClubId": $routeParams.snsClubId,
			"title": title,
			"content": content,
			"fileUploadIds": imgs
		};
		
		snsService.addTopic(param).then(function(data){
			if(data.status ==0){
				$scope.uploadedImages = [];
				$location.path("/club/" + $routeParams.snsClubId).replace();
			}
		});
	};

	$scope.removeImage = function(index){
		$scope.uploadedImages.splice(index,1);
	};

	//WebViewJavascriptBridge
	$scope.addFile = function(){
		$rootScope.isPending = true;
		$scope.isUploadSuccess = false;
		//$rootScope.$apply();
		//$scope.$apply();
		console.log("version", browser.versions)
		if(browser.versions.ios){
			Log.log("try to call ios native to add image");
			if(window.WebViewJavascriptBridge){
				WebViewJavascriptBridge.callHandler('uploadImage', function(response){
					Log.log("call native to upload image");
				});
			}
		}else if(browser.versions.android){
			Log.log("try to call android native to add image");
			jsb.require('uploadImage', {"msg":"show upload image"}, function(response){
			    Log.log("call native to upload image");
			});
		}else{
			console.log("this is desktop");
			// directive in the page will do the rest work
		}
	};
	$scope.toggleEmoji = function(){
		$rootScope.showEmoji = !$rootScope.showEmoji;
		$rootScope.$emit("EMOJI_DISPLAY_UPDATE_EVENT");
	}
}]);

/* image slider controller*/
app.controller("ImageSliderController", ['$location','$scope', "$rootScope",function($location, $scope, $rootScope){
	$scope.visible = false;
	$rootScope.$on("SHOW_IMAGE_SLIDER_EVENT", function(evt,args){
		Log.log("SHOW_IMAGE_SLIDER_EVENT handler: ");
		$rootScope.isSliderOn = true;
		$scope.content = args;
		$scope.visible = true;
				//document.querySelector(".modal-image-slider").style.display = "";
	});
	$rootScope.$on("HIDE_IMAGE_SLIDER_EVENT", function(evt){
		$scope.content = null;
		$rootScope.isSliderOn = false;
		$scope.visible = false;

				//document.querySelector(".modal-image-slider").style.display = "none";
		return;
	});
}]);

app.controller("VoterValidationController", ['$location','$scope', "$rootScope", 'snsService','$modal', function($location, $scope, $rootScope, snsService,$modal){
    $rootScope.notHaveHeader=true;
    $rootScope.hasFooter = false;
	if(localStorage.getItem('employeeVote_Voter'))//已经验证过，直接进入投票页面
		$location.path("/employeeVote");
	$rootScope.pageTitle = "投票";
	$rootScope.isPending = false;
	$scope.confirm = function(){
		var info = {
			'voter': $scope.voter,
			'password': $scope.password
		};
		snsService.validateVoter(info).then(function(data){
			if (data.status == 0)
			{
				localStorage.setItem('employeeVote_Voter',info.voter);
				localStorage.setItem('employeeVote_VoterPassword',info.password);
				$location.path("/employeeVote");
			} else
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: data.friendlyMessage};
						}
					}
				});
			}
		});

	}
}]);

app.controller("EmployeeVoteController", ['$scope', '$location', '$rootScope', 'snsService','$modal', function($scope, $location, $rootScope, snsService,$modal){
	$rootScope.pageTitle = "投票";
	$rootScope.isPending = false;
	$rootScope.showBackButton = false;
    $rootScope.notHaveHeader=true;
    $rootScope.hasFooter = false;
	$scope.hasSelected=false;//什么都不选中
    $scope.isSupport=true;
	$scope.selectOption=function(value)
	{
        $scope.hasSelected=true;
        $scope.isSupport=value;
	};
    $scope.clear=function(){
        localStorage.removeItem('employeeVote_Voter' );
    }
	$scope.submit = function(){
		var param = {
			'employeeNum': $scope.employeeNum,
			'isSupport': $scope.isSupport,
			'voter':localStorage.getItem('employeeVote_Voter'),
			'password':localStorage.getItem('employeeVote_VoterPassword')
		};
        if(!$scope.employeeNum)
        {
            $scope.requiredEmployeeStyle={border:"1px solid red"};
            return;
        }
        else
        {
            $scope.requiredEmployeeStyle={};
        }
        if(!$scope.hasSelected)//一个都没有选择
            snsService.voteEmployee(param).then(function(data){
                var modalInstance = $modal.open({
                    templateUrl: 'views/tmpl_modal_alert.html',
                    controller: ModalAlertCtrl,
                    size: 'sm',
                    resolve: {
                        alertObj: function () {
                            return {message: "请选择赞或者投诉!"};
                        }
                    }
                });
            })
        else {
            $scope.param=param;
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_vote_employee_confirm.html',
                controller: ModalConfirmVoteEmployeeMsgCtrl,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return {message:"您确认"+(param.isSupport?"赞":"投诉")+"该员工"+param.employeeNum+"吗?",scope:$scope};
                    }
                }
            });
        }
	};
}]);

app.controller("ChoosePayTypeController", ['$location','$scope', "$rootScope", 'snsService','$modal','$routeParams','nativeService',
    function($location, $scope, $rootScope, snsService,$modal,$routeParams,nativeService){
    $rootScope.pageTitle = "选择支付类型";
    $rootScope.pageClass = "page-enroll";
    $rootScope.canCreateTopic = false;
    $rootScope.canRemoveAction = false;
    $rootScope.isPending=false;
    $rootScope.hasFooter = false;
	snsService.getPayType().then(function(data){
		$scope.payTypes=data.data;
	});
    $scope.selectIndex=0;
    $scope.payScene=$routeParams.payScene;
    $scope.selectOption=function(index)
    {
        $scope.selectIndex=index;
        for (var i in  $scope.payTypes)
        {
            $scope.payTypes[i].checked=0;
        }

        $scope.payTypes[$scope.selectIndex].checked=1;
    }
    $scope.next=function()
    {
        if (parseInt($scope.payScene)==payScene.LDE)//报名学车
        {
            $rootScope.isPending=true;
            var param={
                "learnDrivingPayOrderId":$rootScope.learnDrivingPayOrderId,
                "payType":$scope.payTypes[$scope.selectIndex].payTypeId
            };
            snsService.updateLDEPayOnlineType(param).then(function(data){
                $rootScope.isPending=false;
                if(data.status==0) {
                    nativeService.setPayCallbackUrl(data.data.payUrl,"/enrollStatus");
                }
                else
                {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/tmpl_modal_alert.html',
                        controller: ModalAlertCtrl,
                        size: 'sm',
                        resolve: {
                            alertObj: function () {
                                return {message:data.friendlyMessage};
                            }
                        }
                    });
                }
            });
        }
    }
}]);

//---------快速佳通事故处理-----------
app.controller("accidentMenuController", ['$scope', '$location', '$rootScope', 'snsService', '$modal',
    function ($scope, $location, $rootScope, snsService, $modal){
        $rootScope.pageTitle = "交通事故快速处理";
        initRootScope($rootScope);
        $scope.setAgreement = function(){
            $location.path("/accident/agreement/menu").search({backUrl:'/accident'});
        };
        $scope.setDissent = function(){
            $location.path("/accident/dissent").search({backUrl:'/accident'});
        };
        $scope.viewAccidentCase = function(){
            $location.path("/accident/caseMenu").search({backUrl:'/accident'});
        };
        $scope.carInfo = function()
        {
            $location.path("/accident/carInfo/enroll").search({backUrl:'/accident'});
        };
    }]);

app.controller('accidentAgreementController', ['$scope', '$location', '$rootScope', '$routeParams', 'snsService', '$modal', function ($scope, $location, $rootScope, $routeParams, snsService, $modal) {
    $rootScope.pageTitle = "快速处理协议";
    initRootScope($rootScope);
    $scope.initDuty = function () {
        for (i in aDuty) {
            aDuty[i].checked = false;
        }
        for (i in bDuty) {
            bDuty[i].checked = false;
        }
    }
    for (i in accidentCaseType) {
        accidentCaseType[i].checked = false;
    }
    for (i in aDuty) {
        aDuty[i].checked = false;
    }
    for (i in bDuty) {
        bDuty[i].checked = false;
    }
    $scope.accidentCase = accidentCaseType;
    $scope.select = false;
    $scope.aType = aDuty;
    $scope.bType = bDuty;
    var myDate = new Date().Format("yyyy-MM-dd hh:mm:ss");
    $scope.agr = {};
	var perChecked = -1;
	var aChecked = -1;
	var bChecked = -1;
    if ($rootScope.accidentAgreement)//全责方直接签署协议
    {
		perChecked =$rootScope.accidentAgreement.accidentCaseTypeId - 1;
		aChecked =$rootScope.accidentAgreement.a_DutyType - 1;
		bChecked =$rootScope.accidentAgreement.b_DutyType - 1;
		$scope.accidentCase[$rootScope.accidentAgreement.accidentCaseTypeId - 1].checked = true;
        $scope.aType[$rootScope.accidentAgreement.a_DutyType - 1].checked = true;
        $scope.bType[$rootScope.accidentAgreement.b_DutyType - 1].checked = true;
        $scope.agr.a_idType = $rootScope.accidentAgreement.a_idType;
        $scope.agr.b_idType = $rootScope.accidentAgreement.b_idType;
		$scope.select = $rootScope.accidentAgreement.abandonInsuranceCompensation;
        $scope.agr = $rootScope.accidentAgreement;
    } else//无责方生成协议并签署
    {
        $scope.agr.a_idType = '身份证';
        $scope.agr.b_idType = '身份证';
        $scope.agr.accidentTime = myDate;
		if($rootScope.tempCarInfo)//如果用户已经登记过车牌信息，直接用用户的车辆信息填充
		{
			$scope.agr.a_Name = $rootScope.tempCarInfo.name;
			$scope.agr.a_idType = $rootScope.tempCarInfo.idType;
			$scope.agr.a_VehicleNum= $rootScope.tempCarInfo.vehicleNum;
			$scope.agr.a_Phone = $rootScope.tempCarInfo.phoneNum;
			$scope.agr.a_InsuranceCompany = $rootScope.tempCarInfo.insuranceCompany;
			$scope.agr.a_idNum = $rootScope.tempCarInfo.idNum;
		}
    }

    $scope.selectOption = function (index) {
        if (perChecked != -1) {
            $scope.accidentCase[perChecked].checked = false;
        }
        $scope.accidentCase[index].checked = !$scope.accidentCase[index].checked;
        perChecked = index;
    };

    $scope.aSelect = function (index) {
        $scope.initDuty();
        $scope.aType[index].checked = true;
        $scope.bType[1 - index].checked = true;
        aChecked = index;
        bChecked = 1 - index;
    };
    $scope.bSelect = function (index) {
        $scope.initDuty();
        $scope.bType[index].checked = true;
        $scope.aType[1 - index].checked = true;
        bChecked = index;
        aChecked = 1 - index;
    }

    $scope.giveUp = function (value) {
        $scope.select = !value;
    };

    //调用签署service后回调
    $scope.$on('signServiceCallback',function(event,data) {
        if(data.status==0)
            $location.path("/accident");
    });

    //提示确认签署回调(无责方生成并且确认情况)
    $scope.$on('genAndSignConfirmCallback',function(event,data){
        $scope.agr.accidentCaseTypeId = $scope.accidentCase[perChecked].AccidentCaseTypeId;
        $scope.agr.a_DutyType = $scope.aType[aChecked].checkId;
        $scope.agr.b_DutyType = $scope.bType[bChecked].checkId;
        $scope.agr.abandonInsuranceCompensation = $scope.select;
        $scope.agr.accidentCaseDescription = null;
        params = $scope.agr;
        snsService.genAndSignAgreement(params).then(function(data){
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_common_alert.html',
                controller: ModalCommonMsgCtrl,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return {message: data.friendlyMessage,scope:$scope,callback:"signServiceCallback",status:data.status};
                    }
                }
            })
        });
    });

    //提示确认签署回调(全责方确认情况)
    $scope.$on('signConfirmCallback', function (event, data) {
        params = {"accidentAgreementId": $scope.agr.accidentAgreementId};
        snsService.signAccidentAgreement(params).then(function (data) {
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_common_alert.html',
                controller: ModalCommonMsgCtrl,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return {
                            message: data.friendlyMessage,
                            scope: $scope,
                            callback: "signServiceCallback",
                            status: data.status
                        };
                    }
                }
            });
        });
    })

    $scope.aleave = function()
    {
        params = $scope.agr.a_VehicleNum;
        if(params.vehicleNum == undefined){
            return;
        }
        snsService.getLatestCarInfoByVehicleNum(params).then(function(data){
            if(data.status == 0)
            {
                $scope.agr.a_Name = data.data.name;
                $scope.agr.a_Phone = data.data.phoneNum;
                $scope.agr.a_idType = data.data.idNum;
                $scope.agr.a_idNum = data.data.idType;
                $scope.agr.a_InsuranceCompany = data.data.insuranceCompany;
            }
        })
    }

    $scope.bleave = function()
    {
        params = {"vehicleNum": $scope.agr.b_VehicleNum};
        if(params.vehicleNum == undefined){
            return;
        }
        snsService.getLatestCarInfoByVehicleNum(params).then(function(data){
            if(data.status == 0)
            {
                $scope.agr.b_Name = data.data.name;
                $scope.agr.b_Phone = data.data.phoneNum;
                $scope.agr.b_idType = data.data.idType;
                $scope.agr.b_idNum = data.data.idNum;
                $scope.agr.b_InsuranceCompany = data.data.insuranceCompany;
            }
        })
    }
    $scope.agree = function()
    {
		var phoneReg = /^\d{6,11}$/;
		var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
		if(!$scope.agr.accidentAddress)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve:{
					alertObj: function(){
						return{message: '请输入事故地点'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.a_VehicleNum)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人A车牌号'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.a_Name)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人A姓名'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.a_Phone)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人A手机号'};
					}
				}
			});
			return;
		}
		if ( !$scope.agr.a_Phone.match(phoneReg))  //判断手机号是否输入正确
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请输入当事人A正确的手机号码'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.a_idNum)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人A证件号'};
					}
				}
			});
			return;
		}
		if(reg.test($scope.agr.a_idNum) === false && $scope.agr.a_idType=="身份证")
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请输入当事人A正确的身份证号'};
					}
				}
			});
			return  false;
		}
		if (!$scope.agr.a_InsuranceCompany)
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请输入当事人A保险公司'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.b_VehicleNum)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人B车牌号'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.b_Name)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人B姓名'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.b_Phone)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人B手机号'};
					}
				}
			});
			return;
		}
		if (!$scope.agr.b_Phone.match(phoneReg))  //判断手机号是否输入正确
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请输入当事人B正确的手机号码'};
					}
				}
			});
			return;
		}
		if(!$scope.agr.b_idNum)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller:ModalAlertCtrl,
				size:'sm',
				resolve:{
					alertObj:function(){
						return {message:'请输入当事人B证件号'};
					}
				}
			});
			return;
		}
		if(reg.test($scope.agr.b_idNum) === false && $scope.agr.b_idType=="身份证")
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请输入当事人B正确的身份证号'};
					}
				}
			});
			return  false;
		}
		if (!$scope.agr.b_InsuranceCompany)
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请输入当事人B保险公司'};
					}
				}
			});
			return;
		}
		if(perChecked==-1 )
		{
			var modalInstance = $modal.open({
			templateUrl:'views/tmpl_modal_alert.html',
			controller: ModalAlertCtrl,
			size: 'sm',
			resolve:{
				alertObj: function(){
					return{message: '请选择事故情形'};
					}
				}
			});
			return;
		}
		if (!$scope.agr.destroySituation)
		{
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message: '请填写伤情及无损情况'};
					}
				}
			});
			return;
		}
		if( aChecked==-1 || bChecked==-1)
		{
			var modalInstance = $modal.open({
				templateUrl:'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve:{
					alertObj: function(){
						return{message: '请选择当事人责任'};
					}
				}
			});
			return;
		}
		if($scope.select == false)
		{
			if (!$scope.agr.a_InsuranceNum)
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: '请输入当事人A保险公司报案号'};
						}
					}
				});
				return;
			}
			if (!$scope.agr.b_InsuranceNum)
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: '请输入当事人B保险公司报案号'};
						}
					}
				});
				return;
			}
		}else{
			if(!$scope.agr.customCompensation)
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请填写自行解决协议赔偿情况'};
						}
					}
				});
				return;
			}
		}
		if($scope.agr.accidentAgreementId)//如果协议ID存在，表示直接签署协议
        {
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_common_confirm.html',
                controller: ModalCommonMsgCtrl,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return {message:"您确认同意签署该协议?",scope:$scope,callback:"signConfirmCallback"};
                    }                    }
            })
        }
        else//否则，生成协议并签署
        {
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_common_confirm.html',
                controller: ModalCommonMsgCtrl,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return { message: "您确认同意签署该协议?", scope: $scope, callback: "genAndSignConfirmCallback" };
                    }
                }
            })
        }
    }
    $scope.updateAIdType = function (idType) {
        $scope.agr.a_idType = idType;
        document.getElementById("aIdType").style.display = "none";
    }
    $scope.displayIdType = function (party) {
        var idTypeId = party == 'a' ? "aIdType" : "bIdType";
        document.getElementById(idTypeId).style.display = "block";
    }
    $scope.updateBIdType = function (idType) {
        $scope.agr.b_idType = idType;
        document.getElementById("bIdType").style.display = "none";
    }
}]);

app.controller('accidentCaseMenuController', ['$scope', '$location', '$rootScope', '$modal', 'caseService',
    function ($scope, $location, $rootScope, $modal, caseService) {
        $rootScope.pageTitle = "单方全责情形列表";
        initRootScope($rootScope);
        $rootScope.accidentCaseId = $rootScope.caseId;
        $scope.select = function (detail) {
            //获取json数据
            caseService.getCase(detail).then(function (data) {
                $rootScope.case = data.case;
                $rootScope.caseId = data.case.caseId;
                $rootScope.pageTitle = data.case.title;
                $location.path("/accident/case/0").search({ backUrl: "/accident/caseMenu" })
                return;
            });
        }

    }]);

app.controller('accidentCaseDetailController', ['$scope', '$location', '$rootScope', '$routeParams', '$modal', function ($scope, $location, $rootScope, $routeParams, $modal) {
    initRootScope($rootScope);
    $rootScope.hasFooter = true;
    $rootScope.gblFooterType = gblFooterType.accidentDetail;
    $scope.curIndex = $routeParams.index;
    $rootScope.curLength = parseInt($scope.curIndex) + 1;
    $scope.array = $rootScope.case.cases;
    $rootScope.totalLength = $scope.array.length;
    var arrayIndex = $scope.array.length - 1;
    $scope.detail = $scope.array[$scope.curIndex];
    $rootScope.showPrevButton = ($scope.curIndex > 0);
    $rootScope.showNextButton = ($scope.curIndex < arrayIndex);
    $rootScope.prev = function () {
        $scope.curIndex--;
        if ($scope.curIndex < 0) {
            $scope.curIndex = 0;
            return;
        }
        var path = "/accident/case/" + ($scope.curIndex);
        $location.path(path);
    }
    $rootScope.next = function () {
        $scope.curIndex++;
        if ($scope.curIndex > $scope.array.length - 1) {
            $scope.curIndex = $scope.array.length - 1;
            return;
        }
        var path = "/accident/case/" + ($scope.curIndex);
        $location.path(path);
    }
    $scope.showOriginalImg = function () { //显示完整图片
        $scope.showMask = !$scope.showMask;
    };
}]);

app.controller('accidentDissentController', ['$scope', '$location', '$rootScope', 'snsService', '$modal',
    function ($scope, $location, $rootScope, snsService, $modal) {
        $rootScope.pageTitle = "双方有异议";
        $rootScope.canRemoveAction = false;
        initRootScope($rootScope);

        $scope.uploadedImages = [];

        document.removeEventListener("FILE_UPLOADED_EVENT");
        document.addEventListener("FILE_UPLOADED_EVENT", function (evt) {
            $rootScope.isPending = false;
            $scope.isUploadSuccess = true;
            $scope.uploadedImages.push(evt.data);
            $rootScope.$$phase || $rootScope.$apply();
            $scope.$$phase || $scope.$apply();
        }, false);

        document.removeEventListener("FILE_UPLOAD_CANCEL_EVENT");
        document.addEventListener("FILE_UPLOAD_CANCEL_EVENT", function (evt) {
            $rootScope.isPending = false;
            $rootScope.$$phase || $rootScope.$apply();
        }, false);

        $scope.addImage = function () {
            $rootScope.isPending = true;
            $scope.isUploadSuccess = false;
            if (browser.versions.ios) {
                Log.log("try to call ios native to add image");
                if (window.WebViewJavascriptBridge) {
                    WebViewJavascriptBridge.callHandler('uploadImage', function (response) {
                        Log.log("call native to upload image");
                    });
                }
            } else if (browser.versions.android) {
                Log.log("try to call android native to add image");
                jsb.require('uploadImage', { "msg": "show upload image" }, function (response) {
                    Log.log("call native to upload image");
                });
            }
        };

        $scope.removeImage = function (index) {
            $scope.uploadedImages.splice(index, 1);
        };
        $scope.$on('postDisentConfirmCallback', function (event, data) {
            var imgs = [];
            angular.forEach($scope.uploadedImages, function (obj) {
                imgs.push(obj.fileUploadId);
            });
            var param = {
                "a_VehicleNum": $scope.a_VehicleNum,
                "b_VehicleNum": $scope.b_VehicleNum,
                "description": $scope.description,
                "fileUploadIds": imgs
            };
            snsService.postAccidentDissent(param).then(function (data) {
                var modalInstance = $modal.open({
                    templateUrl: 'views/tmpl_modal_common_alert.html',
                    controller: ModalCommonMsgCtrl,
                    size: 'sm',
                    resolve: {
                        obj: function () {
                            return { message: data.friendlyMessage, scope: $scope, callback: "postDisentServiceCallback", status: data.status };
                        }
                    }
                });
            })
        });
        $scope.$on('postDisentServiceCallback', function (event, data) {
            if (data.status == 0)
                $location.path("/accident");
        })
        $scope.submit = function () {
			if(!$scope.a_VehicleNum)
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入当事人A车牌号'};
						}
					}
				});
				return;
			}
			if(!$scope.b_VehicleNum)
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入当事人B车牌号'};
						}
					}
				});
				return;
			}
			if(!$scope.description)
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入情形描述'};
						}
					}
				});
				return;
			}
			if($scope.uploadedImages == "")
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请上传照片'};
						}
					}
				});
				return;
			}
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_common_confirm.html',
                controller: ModalCommonMsgCtrl,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return { message: "您确认提交处理申请?", scope: $scope, callback: "postDisentConfirmCallback" };
                    }
                }
            });
        }
    }]);

app.controller('accidentAgreementMenuController',['$scope', '$location', '$rootScope',  '$modal', 'snsService',
    function($scope, $location, $rootScope,  $modal, snsService){
        $rootScope.pageTitle = "双方达成协议";
        initRootScope($rootScope);
        $scope.generationAgreement=function(){
			$rootScope.accidentAgreement=null;
            $location.path("/accident/agreement").search({backUrl:'/accident/agreement/menu'});
        }
        $scope.Agreement = function(){
            $location.path("/accident/agreement/get").search({backUrl:'/accident/agreement/menu'});
        }	}]);

app.controller('accidentAgreementGetController', ['$scope', '$location', '$rootScope', 'snsService', '$modal',
    function ($scope, $location, $rootScope, snsService, $modal) {
        $rootScope.pageTitle = "无责方获取协议";
        initRootScope($rootScope);
        $scope.getAgreement = function () {
            var params = { vehicleNum: $scope.vehicleNum };
            snsService.getCurUnsignedAccidentAgreement(params).then(function (data) {
                if (data.status == 0) {
                    $rootScope.accidentAgreement = data.data;
                    $location.path("/accident/agreement");
                }
                else {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/tmpl_modal_alert.html',
                        controller: ModalAlertCtrl,
                        size: 'sm',
                        resolve: {
                            alertObj: function () {
                                return { message: data.friendlyMessage };
                            }
                        }
                    });
                }
            })
        }
    }]);

app.controller('accidentCarInfoEnrollController', ['$scope','$location', '$rootScope','$routeParams',  '$modal', 'snsService',
    function($scope, $location, $rootScope, $routeParams,  $modal, snsService){
        $rootScope.pageTitle = "车辆信息登记";
        initRootScope($rootScope);
		$rootScope.idTypeOptionValue = "身份证";
		$scope.updateAIdType= function (idType) {
            $rootScope.idTypeOptionValue = idType;
        }
		snsService.getLatestCarInfo().then(function (data) {
                if (data.status == 0) {
                    $rootScope.tempCarInfo = data.data;
					$rootScope.idTypeOptionValue=$rootScope.tempCarInfo.idType;
                }
            })

        $scope.Submit =function(){
			var phoneReg = /^\d{6,11}$/;
			var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
			$rootScope.tempCarInfo.idType = $rootScope.idTypeOptionValue;
			if(!$rootScope.tempCarInfo.vehicleNum)//判断车牌号是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入车牌号'};
						}
					}
				});
				return;
			}
			if(!$rootScope.tempCarInfo.name)//判断姓名是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入姓名'};
						}
					}
				});
				return;
			}
			if(!$rootScope.tempCarInfo.phoneNum)//判断手机号是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入手机号'};
						}
					}
				});
				return;
			}
			if (!$rootScope.tempCarInfo.phoneNum.match(phoneReg))  //判断手机号是否输入正确
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: '请输入正确的手机号码'};
						}
					}
				});
				return;
			}
			if(!$rootScope.tempCarInfo.idNum)//判断身份证是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入证件号'};
						}
					}
				});
				return;
			}
			if(  $rootScope.tempCarInfo.idType=="身份证" && reg.test($rootScope.tempCarInfo.idNum) === false )////判断身份证是否输入正确
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: '请输入正确的身份证号'};
						}
					}
				});
				  return  false;
			}
			if(!$rootScope.tempCarInfo.insuranceCompany)//判断保险公司是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入保险公司'};
						}
					}
				});
				return;
			}
            if($rootScope.tempCarInfo.carInfoId)
            {
                params = $rootScope.tempCarInfo;
                snsService.updateCarInfo(params).then(function (data) {
                    if (data.status == 0) {
                       // $rootScope.temp = data;
                        $location.path("/accident");
                    } else {
                        var modalInstance = $modal.open({
                            templateUrl: 'views/tmpl_modal_alert.html',
                            controller: ModalAlertCtrl,
                            size: 'sm',
                            resolve: {
                                alertObj: function () {
                                    return {message: data.friendlyMessage};
                                }
                            }
                        })
                    }
                })
            }else{
                var params = $rootScope.tempCarInfo;
                snsService.enrollCarInfo(params).then(function (data) {
                    if (data.status == 0) {
                        $rootScope.tempCarInfo = data.data;
                        $location.path("/accident");
                    } else {
                        var modalInstance = $modal.open({
                            templateUrl: 'views/tmpl_modal_alert.html',
                            controller: ModalAlertCtrl,
                            size: 'sm',
                            resolve: {
                                alertObj: function () {
                                    return {message: data.friendlyMessage};
                                }
                            }
                        })
                    }
                })
            }
        }
    }]);

app.controller('accidentCarInfoPromptEnrollController', ['$scope','$location', '$rootScope','$routeParams',  '$modal', 'snsService',
    function($scope, $location, $rootScope, $routeParams,  $modal, snsService){
        initRootScope($rootScope);
        $rootScope.pageTitle = "车辆信息登记";
        $rootScope.tempCarInfo={};
		$rootScope.tempCarInfo.idType = "身份证";
        $scope.updateAIdType= function (idType) {
            $scope.tempCarInfo.idType = idType;
            document.getElementById("aIdType").style.display="none";
        }
        $scope.displayIdType= function (party) {
            var idTypeId= party == 'a' ? "aIdType" : "bIdType";
            document.getElementById(idTypeId).style.display="block";
        }
        $scope.Submit = function(){
            $rootScope.refer = true;
            var params = $rootScope.tempCarInfo;
			var phoneReg = /^\d{6,11}$/;
			var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
			if(!$rootScope.tempCarInfo.vehicleNum)//判断车牌号是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入车牌号'};
						}
					}
				});
				return;
			}
			if(!$rootScope.tempCarInfo.name)//判断姓名是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入姓名'};
						}
					}
				});
				return;
			}
			if(!$rootScope.tempCarInfo.phoneNum)//判断手机号是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入手机号'};
						}
					}
				});
				return;
			}
			if (!$rootScope.tempCarInfo.phoneNum.match(phoneReg))  //判断手机号是否输入正确
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: '请输入正确的手机号码'};
						}
					}
				});
				return;
			}
			if(!$rootScope.tempCarInfo.idNum)//判断身份证是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入证件号'};
						}
					}
				});
				return;
			}
			if($rootScope.tempCarInfo.idType=="身份证" && reg.test($rootScope.tempCarInfo.idNum) === false  )
			{
				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {
							return {message: '请输入正确的身份证号'};
						}
					}
				});
				return  false;
			}
			if(!$rootScope.tempCarInfo.insuranceCompany)//判断保险公司是否有输入
			{
				var modalInstance = $modal.open({
					templateUrl:'views/tmpl_modal_alert.html',
					controller:ModalAlertCtrl,
					size:'sm',
					resolve:{
						alertObj:function(){
							return {message:'请输入保险公司'};
						}
					}
				});
				return;
			}
            snsService.enrollCarInfo(params).then(function(data){
                if(data.status == 0)
                {
                    $rootScope.tempCarInfo = data.data;
                    $location.path("/accident");
                }else
                {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/tmpl_modal_alert.html',
                        controller: ModalAlertCtrl,
                        size: 'sm',
                        resolve: {
                            alertObj: function () {
                                return {message: data.friendlyMessage};
                            }
                        }
                    })
                }
            })
        }

        $scope.Skip = function()
        {
            $rootScope.nextStep = true;
            $location.path("/accident");
        }
    }]);

app.controller('accidentNavController', ['$scope', '$rootScope','$location', 'snsService',
    function($scope, $rootScope, $location, snsService){
        initRootScope($rootScope);
        $rootScope.notHaveHeader=true;
        if(!$rootScope.nextStep && !$rootScope.refer)
        {
            snsService.getLatestCarInfo().then(function(data){
                if(data.status == 0)
                {
                    $rootScope.tempCarInfo = data.data;
                    $location.path("/accident");
                }else{
                    $location.path("/accident/carInfo/promptEnroll");
                }
            })
        }
    }]);
//---------快速佳通事故处理结束-----------

//文明交通--开始
app.controller("AwardController", ['$location', '$scope', "$rootScope", 'snsService', '$modal', '$routeParams', "$http", 'awardService',
    function ($location, $scope, $rootScope, snsService, $modal, $routeParams, $http, awardService) {
        $rootScope.pageTitle = "文明交通天天有奖参与";
        $rootScope.pageClass = "page-award";
        $rootScope.canCreateTopic = false;
        $rootScope.canRemoveAction = false;
        $rootScope.isPending = false;
        $rootScope.hasFooter = true;
        $rootScope.gblFooterType = gblFooterType.award;

        $scope.start = function () {
            $rootScope.questionsLoaded = false;
            snsService.getAwardQuestionList().then(function (response) {
                if (response && response.data) {
                    $http.get("dummy/subject1.json?t=" + Math.random() * 100000).then(function (exams) {
                        $rootScope.curExam = exams.data.exam;

                        var questionId = -1;
                        var qs = awardService.getQuestions();
                        var answers = awardService.getAnswers();
                        // is in progress
                        if (qs && answers && qs.startDate == response.data.startDate) {
                            $rootScope.curQuestions = answers;
                            for (var i = 0; i < answers.length; i++) {
                                if (!answers[i].answered) {
                                    questionId = i;
                                    break;
                                }
                            }
                        }
                        else {
                            awardService.setQuestions(response.data);
                            qs = response.data.titleIds;
                            $rootScope.curQuestions = $rootScope.curExam.questions.filter(function (val) {
                                return qs.indexOf(val.id * 1) > -1;
                            });
							awardService.setAnswers($rootScope.curQuestions);
                            questionId = 0;
                        }
                        if (questionId == -1) {// finished
                            $location.path("/award/done");
                        }
                        else if ($rootScope.curQuestions.length > 0) {// first unanswered question
                            $location.path("/award/question/" + questionId);
                        }
                    });
                }
            });
        }
        $scope.ranking = function () {
            $rootScope.isAwardRankingLoaded = false;
            $location.path("/award/ranking");
        }

        $scope.myScore = function () {
            $location.path("/award/myscore");
        }
    }]);

app.controller("AwardDoneController", ['$location', '$scope', "$rootScope", 'snsService', '$modal', '$routeParams',
    function ($location, $scope, $rootScope, snsService, $modal, $routeParams) {
        $rootScope.pageTitle = "文明交通天天有奖参与";
        $rootScope.pageClass = "page-award";
        $rootScope.canCreateTopic = false;
        $rootScope.canRemoveAction = false;
        $rootScope.isPending = false;
        $rootScope.hasFooter = false;

        $scope.done = function () {
			snsService.getClubByName(TRAFFIC_ANSWER_SNS_CLUB_NAME ).then(function(resp){
				$location.path("/club/"+resp.data.snsClubId);
			});
        }
    }]);

app.controller("AwardRankingController", ['$location', '$scope', "$rootScope", 'snsService', '$modal', '$routeParams',
    function ($location, $scope, $rootScope, snsService, $modal, $routeParams) {
        $rootScope.pageTitle = "积分排行榜";
        $rootScope.pageClass = "page-award";
        $rootScope.canCreateTopic = false;
        $rootScope.canRemoveAction = false;
        $rootScope.isPending = false;
        $rootScope.hasFooter = false;

        // init data
        $scope.rankTypes = { "year": 1, "quater": 2, "month": 3, "day": 4 };
        $scope.currentPage = 1;
        $scope.counterPerpage = 100;
        //$scope.currentType = $scope.rankTypes.year;

        $scope.setType = function (type) {
            if ($scope.currentType == type)
                return;
            $scope.isLoading = true;

            // init value
            $scope.currentType = type;
            $scope.currentPage = 1;
            $scope.counterPerpage = 30;
            var params = { "page": $scope.currentPage, "countPerPage": $scope.counterPerpage, "rankType": $scope.currentType };
            $scope.scores = null;

            // get year list by default
            snsService.getRankList(params).then(function (response) {
                if (response.status == 0) {
                    if (response.data && response.data.scores) {
                        $scope.scores = response.data.scores;
                    }
                }
                $scope.isLoading = false;
            });
        };

        $scope.goforum = function () {
			snsService.getClubByName(TRAFFIC_ANSWER_SNS_CLUB_NAME).then(function(resp){
				$location.path("/club/"+resp.data.snsClubId);
			});
        }

        // load year data by default
        if (!$rootScope.isAwardRankingLoaded) {
            $rootScope.isAwardRankingLoaded = true;
            $scope.setType($scope.rankTypes.year);
        }

        var loadMoreEventHandler = function (evt) {

            if ($scope.isLoading)
                return;

            $scope.isLoading = true;

            var params = { "page": $scope.currentPage + 1, "countPerPage": $scope.counterPerpage, "rankType": $scope.currentType };

            // get year list by default
            snsService.getRankList(params).then(function (response) {
                if (response.status == 0) {
                    if (response.data && response.data.scores) {
                        if ($scope.scores) {
                            $scope.scores = $scope.scores.concat(response.data.scores);
                        }
                        else {
                            $scope.scores = response.data.scores;
                        }
                        $scope.isLoading = false;
                        $scope.currentPage = $scope.currentPage + 1;
                    }
                    else {
                        $scope.noMorePage = true;
                    }
                }
            });
        };

        // remove the event listener
        $rootScope.$$listeners["LOAD_MORE_TITLES_EVENT"] = [];
        $rootScope.$on("LOAD_MORE_TITLES_EVENT", loadMoreEventHandler);
        //$rootScope.$on("REFRESH_TITLES_EVENT", getTopics);
    }]);

app.controller("AwardMyScoreController", ['$location', '$scope', "$rootScope", 'snsService', '$modal', '$routeParams',
    function ($location, $scope, $rootScope, snsService, $modal, $routeParams) {
        $rootScope.pageTitle = "我的积分";
        $rootScope.pageClass = "page-award";
        $rootScope.canCreateTopic = false;
        $rootScope.canRemoveAction = false;
        $rootScope.isPending = false;
        $rootScope.hasFooter = false;

        snsService.getMyScore().then(function (response) {
            if (response.status == 0 && response.data) {
                $scope.scores = [];
                $scope.scores.push({ name: "年度", score: response.data.yearScore });
                $scope.scores.push({ name: "季度", score: response.data.quaterScore });
                $scope.scores.push({ name: "月度", score: response.data.monthScore });
                $scope.scores.push({ name: "今日", score: response.data.dayScore });
            }

        });
    }]);

app.controller("AwardQuestionController", ['$location', '$scope', "$rootScope", "$routeParams", "$interval", 'awardService', 'snsService',
    function ($location, $scope, $rootScope, $routeParams, $interval, awardService, snsService) {
        $rootScope.pageTitle = "参与答题";
        $rootScope.pageClass = "page-award";
        $rootScope.canCreateTopic = false;
        $rootScope.canRemoveAction = false;
        $rootScope.isPending = false;
        $rootScope.hasFooter = true;
        $rootScope.gblFooterType = gblFooterType.awardQuestion;

        var curQuestionId = $routeParams.questionId * 1;
        $scope.curQuestionId = curQuestionId + 1;

        $rootScope.showBackButton = true;

        $scope.question = $rootScope.curQuestions[curQuestionId];
        $scope.question.mutiple = $scope.question.answer.length > 1;
        $scope.question.selectedMutiAnswer = [];
        $scope.question.correctResult = toAnswer($scope.question.answer);

        $rootScope.currentIndex = (curQuestionId + 1) + "/" + $rootScope.curQuestions.length;
        $rootScope.curQuestionId = curQuestionId;
        $rootScope.showPrevButton = curQuestionId != 0;
        $rootScope.showNextButton = curQuestionId < $rootScope.curQuestions.length - 1;

        // show finished button
        if (curQuestionId >= $rootScope.curQuestions.length - 1) {
            $rootScope.showFinishButton = true;
            for (var i = 0; i < $rootScope.curQuestions.length - 1; i++) {
                if (!$rootScope.curQuestions[i].answered) {
                    $rootScope.showFinishButton = false;
                    break;
                }
            }
        }

        if (!$scope.question.status)
            $scope.question.status = [];

        $rootScope.prev = function () {
            if ($rootScope.curQuestionId > 0) {
                var path = "award/question/" + ($rootScope.curQuestionId - 1);
                $location.path(path);
            }
        }
        $rootScope.next = function () {
            if ($rootScope.curQuestionId < $rootScope.curQuestions.length - 1) {
                var path = "award/question/" + ($rootScope.curQuestionId + 1);
                $location.path(path);
            }
        }

        $scope.selectOpetion = function (index) {

            if ($scope.question.answered)
                return;

            if ($scope.question.mutiple) {
                if ($scope.question.status[index] == 1) {
                    $scope.question.status[index] = 0;
                    $scope.question.selectedMutiAnswer[index] = 0;
                }
                else {
                    $scope.question.status[index] = 1;
                    $scope.question.selectedMutiAnswer[index] = index + 1;
                }
            }
            else {
                $scope.question.selectedAnswer = index + 1;
                $scope.question.status[index] = 1;
                $scope.answerChanged();
            }
        }

        $scope.answerChanged = function () {
            $scope.question.answered = true;

            if ($scope.question.mutiple) {
                var r = toAnswer($scope.question.selectedMutiAnswer);
                $scope.question.isCorrect = r == $scope.question.correctResult;
            }
            else {
                $scope.question.isCorrect = $scope.question.selectedAnswer == $scope.question.answer[0];
            }

            for (var i = 0; i < $scope.question.answer.length; i++) {
                var ca = $scope.question.answer[i] * 1 - 1;
                $scope.question.status[ca] = 2;
            }

            for (var i = 0; i < $scope.question.status.length; i++) {
                if ($scope.question.status[i] && $scope.question.status[i] == 1) {
                    $scope.question.status[i] = 3;
                }
            }

            if ($scope.question.isCorrect) {
                $rootScope.next();
            }

            // post result
            var body = { "titleId": $scope.question.id, "isCorrect": $scope.question.isCorrect };
            snsService.awardAnswerQuestion(body).then(function (result) {
                if (result && result.status == 0) {
                    // save result
                    awardService.setAnswers($rootScope.curQuestions);
                }
            });
        }

        $rootScope.finish = function () {
            if (!$scope.question.answered)
                return;
            $location.path("/award/done");
        }
    }]);

function toAnswer(array) {
    var result = "";
    if (array != null) {
        for (var i = 0; i < array.length; i++) {
            if (array[i] == undefined)
                continue;
            var r = "";
            switch (array[i] * 1) {
                case 1:
                    r = "A,";
                    break;
                case 2:
                    r = "B,";
                    break;
                case 3:
                    r = "C,";
                    break;
                case 4:
                    r = "D,";
                    break;
            }
            result += r;
        }
    }
    result = result.substring(0, result.length - 1);
    return result;
}
//文明交通--结束/* modal controllers */

var ModalCommonMsgCtrl = function ($scope, $rootScope, $modalInstance, $modal, snsService, obj) {
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    $scope.confirm = function (callback) {
        $modalInstance.dismiss('cancel');
        if (callback)
            obj.scope.$emit(callback, obj);
    };
    $scope.obj = obj;
};


/* modal controllers */
var ModalConfirmCtrl = function ($location,$scope, $rootScope, $modalInstance, $modal, snsService, enrollInfo) {
	//var careerData = angular.fromJson(roleInfo);
	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
	};
	$scope.confirm = function(){
		snsService.apply(enrollInfo).then(function(data){
			//console.log("=======", data)
			$modalInstance.dismiss('cancel');
			if(data.status==0){
				//alert(data.friendlyMessage);
                if ($rootScope.enrollInfo.payMethod==payMethod.payAllOnline||
					$rootScope.enrollInfo.payMethod==payMethod.prepaidOnline )
                {
                    $rootScope.learnDrivingPayOrderId=data.data.learnDrivingPayOrderId;
                    $location.path("/choosePayType/"+payScene.LDE);
                }
                else
                {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/tmpl_modal_alert.html',
                        controller: ModalAlertCtrl,
                        size: 'sm',
                        resolve: {
                            alertObj: function () {
                                return {message:data.friendlyMessage, success:true};
                            }
                        }
                    });
                }
		
			}else{
				var errMessage = data.friendlyMessage || "error";

				var modalInstance = $modal.open({
					templateUrl: 'views/tmpl_modal_alert.html',
					controller: ModalAlertCtrl,
					size: 'sm',
					resolve: {
						alertObj: function () {							
							return {message:errMessage};
						}
					}
				});
			}
		});		
		
	};
};

var ModalConfirmRemoveInteractionMsgCtrl = function ($scope, $rootScope, $modalInstance, $modal, snsService, obj) {
	//var careerData = angular.fromJson(roleInfo);
	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
	};
	$scope.confirm = function(){
		snsService.clearMyInteractionMsgs().then(function(data){
			$modalInstance.dismiss('cancel');
			obj.scope.actions=[];
			obj.scope.showMore=false;
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {
						return {message:data.friendlyMessage};
					}
				}
			});
		});
	};
	$scope.obj = obj;
};

var ModalConfirmVoteEmployeeMsgCtrl = function ($scope, $rootScope, $modalInstance, $modal, snsService, obj) {
    //var careerData = angular.fromJson(roleInfo);
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    };
    $scope.confirm = function(){
        snsService.voteEmployee(obj.scope.param).then(function(data){
            $modalInstance.dismiss('cancel');
            obj.scope.employeeNum="";
            var modalInstance = $modal.open({
                templateUrl: 'views/tmpl_modal_alert.html',
                controller: ModalAlertCtrl,
                size: 'sm',
                resolve: {
                    alertObj: function () {
                        return {message:data.friendlyMessage};
                    }
                }
            });
        });
    };
    $scope.obj = obj;
};

var ModalAlertCtrl = function ($scope, $location, $rootScope, $modalInstance, snsService, alertObj) {
	//var careerData = angular.fromJson(roleInfo);
	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
		if(alertObj.success){
			//WebViewJavascriptBridge.callHandler('exitUIWebView');
			$location.path("/enrollStatus");
		}
	};
	$scope.alertObj = alertObj;
	
};


var ModalAddReplyCtrl = function ($scope, $rootScope, $modalInstance, focus, snsService, replyObj) {
	//var careerData = angular.fromJson(roleInfo);
	focus('focusMe');
	$scope.replyObj = replyObj;
	$rootScope.showEmoji = true;
	$scope.cancelReply = function(snsTopicId){
		$rootScope.showEmoji = false;
		$(".textarea-reply").val("");
		$modalInstance.dismiss('cancel');
	};
	$scope.replyValue;
	var isSending = false;
	console.log("========")
	console.log(replyObj)
	$scope.replyTo = replyObj.replyTo;
	var emojinum = 0;
	$rootScope.$$listeners["EMOJI_SELECTED_EVENT"]=[];
	$rootScope.$on("EMOJI_SELECTED_EVENT",function(evt, args){
			
		$(".textarea-reply").val($(".textarea-reply").val() + args.emotion);
			
		//contentEl.value = contentEl.value + args.emotion;
	});

	$scope.submitReply = function(id){

		var txt = document.querySelector("textarea[name='replyTopic" + id + "']");
		var val = txt.value;
		if(!val)
			return;
		if($.emoticons.count(val) >8){
			$(".note-dialog").show();
			$(".note-dialog").addClass("note-dialog-show");
			setTimeout(function(){
				$(".note-dialog").hide();
				$(".note-dialog").removeClass("note-dialog-show");
			},4000);
			return;
		}
		var params = {
			
			"content": val,
			"imgUrls": []
		}	
		if(isSending)
			return;
		console.log(replyObj.snsTopicId + "; reply id: " + replyObj.snsReplyId)
		if(replyObj.snsTopicId){
			params.snsTopicId = replyObj.snsTopicId;
			snsService.reply(params).then(function(data){
				if(data.status == 0){
					txt.value = '';
					$rootScope.showEmoji = false;
					$(".textarea-reply").val("");
					$modalInstance.dismiss('cancel');

					replyObj.scope.$emit("REFRESH_TOPIC_REPLIES", replyObj.snsTopicId);
					isSending = false;
					
				}
				
			});
		}
		else if(replyObj.snsReplyId){
			params.tosnsReplyId = replyObj.snsReplyId;
			console.log(params)
			snsService.toReply(params).then(function(data){
				console.log("hereh", data)
				if(data.status == 0){
					txt.value = '';
					$rootScope.showEmoji = false;
					$(".textarea-reply").val("");
					$modalInstance.dismiss('cancel');

					replyObj.scope.$emit("REFRESH_TOPIC_REPLIES", replyObj.scope.topic.snsTopicId);
					isSending = false;
					
				}
				
			});
		}
		
		isSending = true;
	};
	
};


var ModalConfirmDeleteCtrl = function ($scope, $rootScope, $modalInstance, $modal, $location, $routeParams, snsService, removeOption) {
	//var careerData = angular.fromJson(roleInfo);
	$scope.isTopic = removeOption.type == "topic";
	$scope.isReply = removeOption.type == "reply";
	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
	};
	var isSending = false;
	$scope.confirm = function(){
		if(isSending)
			return;
		if(removeOption.type=="topic"){
			snsService.removeTopic({snsTopicId:removeOption.snsTopicId}).then(function(data){
				isSending = false;
				$rootScope.$emit("REFRESH_TITLES_EVENT", removeOption.snsTopicId);
				//$location.path("/club/" + $routeParams.snsClubId);
				$modalInstance.dismiss('cancel');
			});

		}
		else if(removeOption.type=="reply"){
			snsService.removeReply({snsReplyId:removeOption.snsReplyId}).then(function(data){
				isSending = false;
				removeOption.scope.$emit("REFRESH_TOPIC_REPLIES", removeOption.snsTopicId);
				$modalInstance.dismiss('cancel');
			});
		}
		isSending = true;

	};
};


var ModalConfirmReportCtrl = function ($scope, $rootScope, $modalInstance, $modal, $location, $routeParams, snsService, reportOption) {
	//var careerData = angular.fromJson(roleInfo);
	$scope.cancel = function () {
		$modalInstance.dismiss('cancel');
	};
	var isSending = false;
	$scope.selecedReason = 0;
	$scope.confirm = function(){
		if(isSending)
			return;
		if($scope.selecedReason == 0)
			return;
		snsService.reportTopic({snsTopicId:reportOption.snsTopicId,snsReportReasonId: $scope.selecedReason}).then(function(data){
			isSending = false;
			$rootScope.$emit("REFRESH_TITLES_EVENT", reportOption.snsTopicId);
			$modalInstance.dismiss('cancel');
			var modalInstance = $modal.open({
				templateUrl: 'views/tmpl_modal_alert.html',
				controller: ModalAlertCtrl,
				size: 'sm',
				resolve: {
					alertObj: function () {							
						return {message:data.friendlyMessage};
					}
				}
			});

		});
		isSending = true;
		
	};

	$scope.updateReportReason = function(val){
		if(!val)
			return;
		console.log("=======" + val + "=======")
		$scope.selecedReason = val;
	}
};

